package restyhttp

import (
	"context"
	"gopkg.in/resty.v1"
	"time"
)

const DefaultTimeout = 10 * time.Second

var restyClientObj *RestyClient

type RestyClient struct {
	Http *resty.Client
}

func InitRestClient() *RestyClient {
	client := resty.New()
	client.SetTimeout(DefaultTimeout)
	client.OnBeforeRequest(clientBeforeRequestMiddleware)
	client.OnAfterResponse(clientHttpMiddleAfter)
	restyClientObj = &RestyClient{
		Http: client,
	}
	return restyClientObj
}

func GetRestyClient() *RestyClient {
	return restyClientObj
}

/**
** restHttp的post请求
** @param ctx  context.Context   context对象
** @param url  string            请求链接
** @param body object           请求参数，一般以map[string]interface的格式
 */
func (r *RestyClient) HttpPostReq(ctx context.Context, URL string, body interface{}, result interface{}) (error) {
	headerParams := make(map[string]string,0)
	headerParams["Content-Type"] = "application/json;charset=utf-8"
	_, err := GetRestyClient().Http.R().
		SetContext(ctx).
		SetHeaders(headerParams).
		SetBody(body).
		SetResult(result).
		Post(URL)
	return err
}

/**
** restHttp的get请求
** @param ctx  context.Context   context对象
** @param url  string            请求链接
** @param query object           请求参数，一般以map[string]interface的格式
** @param result object         请求参数, 一般为struct类型的指针
 */
func (r *RestyClient) HttpGetReq(ctx context.Context, URL string, query map[string]string, result interface{}) (error) {
	headerParams := make(map[string]string,0)
	headerParams["Content-Type"] = "application/json;charset=utf-8"
	_, err := GetRestyClient().Http.R().
		SetContext(ctx).
		SetHeaders(headerParams).
		SetQueryParams(query).
		SetResult(result).
		Get(URL)
	return err
}